<template>
  <div>
    <!--  class="components-container"    -->

    <!--    // handleCreateProduct top 操作栏-->
    <!--  +postForm.status  -->
    <sticky :class-name="'sub-navbar'" :z-index="10">
      <!--      <CommentDropdown v-model="postForm.comment_disabled" />-->
      <!--      <PlatformDropdown v-model="postForm.platforms" />-->
      <!--      <SourceUrlDropdown v-model="postForm.source_uri" />-->


      <!--      <el-dropdown :show-timeout="100" trigger="click">-->
      <!--        <el-button plain>-->
      <!--          {{ !comment_disabled?'评论已打开':'评论已关闭' }}-->
      <!--          <i class="el-icon-caret-bottom el-icon&#45;&#45;right" />-->
      <!--        </el-button>-->
      <!--        <el-dropdown-menu slot="dropdown" class="no-padding">-->
      <!--          <el-dropdown-item>-->
      <!--            <el-radio-group v-model="comment_disabled" style="padding: 10px;">-->
      <!--              <el-radio :label="true">-->
      <!--                关闭评论-->
      <!--              </el-radio>-->
      <!--              <el-radio :label="false">-->
      <!--                打开评论-->
      <!--              </el-radio>-->
      <!--            </el-radio-group>-->
      <!--          </el-dropdown-item>-->
      <!--        </el-dropdown-menu>-->
      <!--      </el-dropdown>-->

      <el-dropdown
        @click="handleCreateComponent"
        split-button trigger="click" type="primary">
        <!--        <el-button-->
        <!--          style="margin-left: 10px;" type="primary">-->
        <!--          新增半成品-->
        <!--        </el-button>-->
        新增半成品
        <el-dropdown-menu class="azure-dropdown" slot="dropdown">
          <el-dropdown-item>
            <el-button
              @click="handleCreateProduct"
              style="margin-left: 10px;" type="success">
              新增产品
            </el-button>
            <el-button
              disabled
              style="margin-left: 10px;" type="primary">
              新增套系
            </el-button>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>


      <!--      <el-button-->
      <!--        disabled-->
      <!--        style="margin-left: 10px;" type="primary">-->
      <!--        编辑产品列表-->
      <!--      </el-button>-->
      <!--      &lt;!&ndash;      v-loading="loading"&ndash;&gt;-->

      <!--      <el-popconfirm-->
      <!--        :title="`是否确定删除下列选定产品？`"-->
      <!--        @confirm="handleDeleteProductList"-->
      <!--        style="margin-left: 10px;">-->
      <!--        <el-button disabled slot="reference" type="info">-->
      <!--          删除产品-->
      <!--        </el-button>-->
      <!--      </el-popconfirm>-->

    </sticky>

    <el-card>

      <el-form
        :label-width="globalLabelWidth" :model="searchFormData" ref="searchDataForm">
        <show-more @getData="getData" @resetSearch="resetSearch">
          <template slot="main">
            <el-row :gutter="globalGutter">

              <el-col v-bind="globalGrid">
                <el-form-item label="产品名称" prop="name">
                  <el-input
                    @keyup.native.enter="getData"
                    clearable
                    placeholder="请输入产品名称"
                    v-model="searchFormData.name">
                    <el-button icon="el-icon-s-grid" slot="append"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col v-bind="globalGrid">
                <el-form-item label="产品编码" prop="code">
                  <el-input
                    @keyup.native.enter="getData"
                    clearable
                    placeholder="请输入产品编码"
                    v-model="searchFormData.code">
                    <el-button icon="el-icon-s-ticket" slot="append"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col v-bind="globalGrid">
                <el-form-item label="产品类型" prop="productType">
                  <product-select
                    placeholder="请选择产品类型"
                    v-model="searchFormData.productType"/>
                </el-form-item>
              </el-col>

            </el-row>
          </template>

          <template slot="more">

            <!--       样例 , 每隔三个重新使用一个row     -->

            <!--            <el-row :gutter="globalGutter">-->
            <!--              <el-col v-bind="globalGrid">-->
            <!--                <el-form-item label="产品类型" prop="productType">-->
            <!--                  <product-select-->
            <!--                    placeholder="请选择产品类型"-->
            <!--                    v-model="searchFormData.productType"/>-->
            <!--                </el-form-item>-->
            <!--              </el-col>-->
            <!--            </el-row>-->

            <el-row :gutter="globalGutter">
              <el-col v-bind="globalGrid">
                <el-form-item label="产品分类" prop="categoricalId">
                  <productCategoricalSelect
                    v-model="searchFormData.categoricalId"
                  />
                </el-form-item>
              </el-col>
              <el-col v-bind="globalGrid">
                <el-form-item label="打印类型" prop="printTypeId">
                  <productPrintType
                    v-model="searchFormData.printTypeId"
                  />
                </el-form-item>
              </el-col>
              <el-col v-bind="globalGrid">
                <el-form-item label="输出类型" prop="shopType">
                  <shop-type-select
                    v-model="searchFormData.shopType"/>
                </el-form-item>
              </el-col>
            </el-row>

            <!--            <el-row :gutter="globalGutter">-->
            <!--              <el-col v-bind="globalGrid">-->
            <!--                <el-form-item label="状态" prop="status">-->
            <!--                  <productStatusSelect-->
            <!--                    v-model="searchFormData.status"/>-->
            <!--                </el-form-item>-->
            <!--              </el-col>-->
            <!--            </el-row>-->

          </template>
        </show-more>
      </el-form>
    </el-card>

    <el-card style="margin-top: 15px">
      <azure-dynamic-table
        :column-des-objs="columnDesObjs"
        :data="tableData"
        :showSeq="true"
        empty-text="没有找到相关的产品|组件|套系,换个关键词和条件搜一搜或点击上方的新增,🤷‍♂️👏👏😢🎉😉✔🐱‍🏍👍🤣👌"
        v-loading="listLoading">
        <template #tableHead>
          <el-alert
            :closable="false"
            :title="alertTitle"
            show-icon
            type="success"
          />
        </template>
        <template slot="operator" slot-scope="{scope:{row,$index}}">
          <AButton @click="handleEditProduct({row,$index})" type="primary">
            {{`编辑${productTypesEnum[row['ProductType']]}`}}
          </AButton>
          <el-popconfirm
            :title="`是否确定删除该${productTypesEnum[row['ProductType']]}？`"
            @confirm="deleteProduct({row,$index,tableData})"
            style="margin-left: 10px;">
            <AButton
              slot="reference" type="info">
              删除
            </AButton>
          </el-popconfirm>

        </template>
      </azure-dynamic-table>

      <pagination :limit.sync="searchFormData.limit" :page.sync="searchFormData.page"
                  :total="total"
                  @pagination="getData"
                  v-show="total>0"/>

    </el-card>

  </div>

</template>

<script>
  //  产品列表
  import { DeleteProduct, ModifyProduct, PageQueryProduct } from '@/api/productInformation'
  import Pagination from '@/components/Pagination/index'
  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  import { ERR_OK } from '@/utils/commons'
  import ShowMore from '@/components/ATheFridayClub/ShowMore'
  import layoutMixin from '@/mixins/layoutMixin'
  import form from '@/mixins/form'
  import Sticky from '@/components/Sticky/index'
  import AButton from '@/components/ATheFridayClub/AButton'
  import ProductSelect from '@/components/ATheFridayClub/businessSelect/product/ProductSelect'
  import productStatusSelect from '@/components/ATheFridayClub/businessSelect/product/productStatusSelect'
  import productCategoricalSelect from '@/components/ATheFridayClub/businessSelect/product/productCategoricalSelect'
  import productPrintType from '@/components/ATheFridayClub/businessSelect/print/productPrintType'
  import { productBaseCols } from '@/views/baseproduct/mixins/productUtil'
  import ShopTypeSelect from '@/components/ATheFridayClub/businessSelect/product/shopTypeSelect'
  import { productTypesEnum } from '@/enums/product'
  import { dataStatusTypesEnum } from '@/enums/common'
  import { objFirstKeyLowerCase } from '@/utils/fridayClub/objectUtil'
  import { debugLogger } from '@/utils/fridayClub/functianal'

  const columnDesObjs = Array.of(
    ...productBaseCols,
    { key: 'operator', label: '操作', width: '200' }
  )

  export default {
    name: 'baseproductinfo',
    components: {
      ShopTypeSelect,
      ProductSelect,
      AButton,
      Sticky,
      ShowMore,
      AzureDynamicTable,
      Pagination,
      productStatusSelect,
      productCategoricalSelect,
      productPrintType
    },
    data() {
      return {
        productTypesEnum,
        columnDesObjs,
        tableData: [],

        listLoading: false,
        searchFormData: {
          name: '', //  产品名

          code: '',//  产品编码
          productType: null,  //  el-select 匹配不到会显示一个奇怪的值,必须为null

          categoricalId: '',
          printTypeId: '',
          shopType: '',
          // status: dataStatusTypesEnum['删除'],
          status: dataStatusTypesEnum['正常'],

          page: 1,
          limit: 10
        },

        total: 0

      }
    },
    computed: {
      alertTitle() {
        return `当前总共查询到了${this.total ? this.total : 0}个(产品|组件|半成品)`
      }
    },
    mixins: [layoutMixin, form],

    created() {
      this.getData()
      //  加载product list 数据

      //  加载各类枚举(放入mixin中?????,感觉不太好)
      //  or 单独抽象成为一个组件      组合要更好一些

    },
    methods: {
      resetSearch() {
        this.resetForm('searchDataForm')
        this.resetPage()
        this.getData()
      },

      resetPage() {
        this.page = 1
      },

      async getData() {
        this.listLoading = true
        const {
          searchFormData: {
            page, limit, name, code, productType, categoricalId,
            printTypeId,
            shopType,
            status
          }
        } = this
        try {
          const { Code, Result } = await PageQueryProduct({
            pageSize: limit,
            pageNum: page,
            name, code, productType,
            categoricalId,
            printTypeId,
            shopType,
            status
          })
          if (Code === ERR_OK) {
            ({ CurrentPage: this.page, RecordCount: this.total, Rows: this.tableData } = Result)
          } else {
            this.$message.error('获取(产品|组件|套系)列表失败😒🎂🤷‍♀️')
          }
        } catch (e) {
          console.log(e)
        } finally {
          this.listLoading = false
        }

      },
      //  对于产品的新增和修改能否抽离出去,便于日后的维护.
      //  视图根据 type 来判断 add or update
      //  新增和修改产品信息
      // beforeAnimateClose() {
      //   //  modifyFormData :: reset
      //
      // },

      //  modifyFormData  = {}
      //  modifyFormStatus =  UPDATE || CREATE
      handleEditProduct({ row, $index } = {}) {
        //  set row 2 modifyFormData
        //  set modifyFormStatus = CREATE
        //  show dialog
        const { ProductId, Code, ProductType } = row
        this.jump2ModifyProduct({ ProductId, Code, ProductType })

      },

      editMode() {
        // table check box 变为 true
      },

      handleDeleteProductList() {
        //  监听 table select 事件 , 赋值给全局deleteRows

      },

      handleDeleteProduct({ row, $index } = {}) {
        //  本地删除

      },

      async deleteProduct({ row, $index, tableData }) {
        // const { tableData } = this
        //  { status } = {}
        try {
          // const { Code, Result } = await ModifyProduct(Array.of(
          //   {
          //     ...objFirstKeyLowerCase(row), status: dataStatusTypesEnum['删除']
          //   })
          // )
          const { ProductTypeTxt, ProductId } = row
          const { Code, Result } = await DeleteProduct(
            Array.of(ProductId)
          )
          if (Code === ERR_OK) {
            if (tableData.length < (this.searchFormData.limit / 2)) {
              this.getData()
            } else {
              tableData.splice($index, 1)
            }
            this.$message.success(`删除${ProductTypeTxt}成功`)
          } else {
            throw new Error(`删除${ProductTypeTxt}`)
          }
        } catch (e) {
          this.$message.error(e)
          console.log(e)
        } finally {
          this.listLoading = false
        }
      },
      handleCreateComponent() {
        this.jump2ModifyProduct({ ProductType: productTypesEnum['组件'] })
      },
      handleCreateProduct() {
        //  createFactory then set
        //  set modifyFormStatus = UPDATE
        //  show dialog
        this.jump2ModifyProduct({ ProductType: productTypesEnum['产品'] })
      },
      jump2ModifyProduct({ ProductId, Code, ProductType } = {}) {
        //   'modifyBaseProductInfo'
        this.$router.push({
          name: (() => {
            if (ProductId) {
              if (ProductType === productTypesEnum['组件']) {
                return 'componentModify'
              }
              return 'editProductInfo'
            } else {
              return 'createProductInfo'
            }
          })(),
          //  ProductType
          query: (() => {
            //  新增时才传产品类型
            const ret = { ProductId, Code }
            return !ProductId ? { ...ret, ProductType } : ret
          })()
        })
      }

    }
  }
</script>

<style lang="scss" scoped>
  .azure-dropdown {
    /deep/ .el-dropdown-menu__item {
      background-color: unset !important;

    }
  }

</style>
